package com.example.controller;

import com.example.entity.Document;
import com.example.mapper.DocumentMapper;
import com.example.service.DocumentService;
import com.example.service.KnowledgeSpaceService;
import com.example.service.MarkdownService;
import com.example.entity.KnowledgeSpace;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.example.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/documents")
public class DocumentController {

    @Autowired
    private DocumentService documentService;

    @Autowired
    private KnowledgeSpaceService knowledgeSpaceService;

    @Autowired
    private MarkdownService markdownService;

    /**
     * 根据空间ID获取文档列表
     */
    @GetMapping("/space/{spaceId}")
    public Result getDocumentsBySpace(@PathVariable Integer spaceId, @RequestParam String username) {
        try {
            if (spaceId == null || spaceId <= 0) {
                return Result.error("空间ID不能为空或无效");
            }
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<Document> documents = documentService.getDocumentsBySpaceId(spaceId);
            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("获取文档列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据文档ID获取文档详情
     */
    @GetMapping("/{documentId}")
    public Result getDocumentById(@PathVariable Integer documentId, @RequestParam String username,
            @RequestParam(defaultValue = "false") Boolean fromRecentOrFavorite) {
        try {
            if (documentId == null || documentId <= 0) {
                return Result.error("文档ID不能为空或无效");
            }
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }

            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 对于最近访问和收藏功能，使用宽松的权限验证 - 暂时禁用权限控制
            // if (!fromRecentOrFavorite) {
            // // 正常访问需要严格的权限验证
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }
            // } else {
            // // 最近访问和收藏功能使用宽松权限验证
            // if (!knowledgeSpaceService.hasRelaxedViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }
            // }

            // 记录访问历史
            documentService.recordDocumentAccess(documentId, username);

            return Result.success(document);
        } catch (Exception e) {
            return Result.error("获取文档详情失败: " + e.getMessage());
        }
    }

    /**
     * 根据关键词搜索文档
     */
    @GetMapping("/search")
    public Result searchDocuments(
            @RequestParam String keyword,
            @RequestParam Integer spaceId,
            @RequestParam String username) {
        try {
            // 检查用户是否有权限访问该知识空间 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<Document> documents = documentService.searchDocumentsByKeyword(keyword, spaceId);
            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("搜索文档失败: " + e.getMessage());
        }
    }

    /**
     * 根据文档标题搜索
     */
    @GetMapping("/search/title")
    public Result searchDocumentsByTitle(
            @RequestParam String title,
            @RequestParam Integer spaceId,
            @RequestParam String username) {
        try {
            // 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<Document> documents = documentService.searchDocumentsByTitle(title, spaceId);
            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("按标题搜索文档失败: " + e.getMessage());
        }
    }

    /**
     * 根据文档内容搜索
     */
    @GetMapping("/search/content")
    public Result searchDocumentsByContent(
            @RequestParam String content,
            @RequestParam Integer spaceId,
            @RequestParam String username) {
        try {
            // 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<Document> documents = documentService.searchDocumentsByContent(content, spaceId);
            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("按内容搜索文档失败: " + e.getMessage());
        }
    }

    /**
     * 根据创建者搜索文档
     */
    @GetMapping("/search/creator")
    public Result searchDocumentsByCreator(
            @RequestParam String creatorUsername,
            @RequestParam Integer spaceId,
            @RequestParam String username) {
        try {
            // 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<Document> documents = documentService.searchDocumentsByCreator(creatorUsername, spaceId);
            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("按创建者搜索文档失败: " + e.getMessage());
        }
    }

    /**
     * 根据文档类型搜索
     */
    @GetMapping("/search/type")
    public Result searchDocumentsByType(
            @RequestParam String documentType,
            @RequestParam Integer spaceId,
            @RequestParam String username) {
        try {
            // 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<Document> documents = documentService.searchDocumentsByType(documentType, spaceId);
            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("按类型搜索文档失败: " + e.getMessage());
        }
    }

    /**
     * 根据文件夹ID获取文档列表
     */
    @GetMapping("/folder/{folderId}")
    public Result getDocumentsByFolderId(@PathVariable Integer folderId, @RequestParam String username) {
        try {
            List<Document> documents = documentService.getDocumentsByFolderId(folderId);

            // 检查权限：如果有文档，检查第一个文档的空间权限
            if (!documents.isEmpty()) {
                Integer spaceId = documents.get(0).getSpaceId();
                // 暂时禁用权限控制
                // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
                // return Result.error("没有访问该知识空间的权限");
                // }
            }

            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("获取文件夹文档失败: " + e.getMessage());
        }
    }

    /**
     * 高级搜索文档
     */
    @GetMapping("/search/advanced")
    public Result advancedSearchDocuments(
            @RequestParam(required = false) String keyword,
            @RequestParam Integer spaceId,
            @RequestParam String username,
            @RequestParam(required = false) String creatorUsername,
            @RequestParam(required = false) String documentType,
            @RequestParam(required = false) Integer folderId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            // 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<Document> documents = documentService.advancedSearchDocuments(
                    keyword, spaceId, creatorUsername, documentType, folderId, startDate, endDate);
            return Result.success(documents);
        } catch (Exception e) {
            return Result.error("高级搜索失败: " + e.getMessage());
        }
    }

    /**
     * 获取搜索建议
     */
    @GetMapping("/search/suggestions")
    public Result getSearchSuggestions(
            @RequestParam String keyword,
            @RequestParam Integer spaceId,
            @RequestParam String username) {
        try {
            // 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(spaceId, username)) {
            // return Result.error("没有访问该知识空间的权限");
            // }

            List<String> suggestions = documentService.getSearchSuggestions(keyword, spaceId);
            return Result.success(suggestions);
        } catch (Exception e) {
            return Result.error("获取搜索建议失败: " + e.getMessage());
        }
    }

    /**
     * 创建新文档
     */
    @PostMapping
    public Result createDocument(@RequestBody Document document, @RequestParam String username) {
        try {
            if (document == null) {
                return Result.error("文档信息不能为空");
            }
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (document.getDocumentName() == null || document.getDocumentName().trim().isEmpty()) {
                return Result.error("文档名称不能为空");
            }
            if (document.getSpaceId() == null || document.getSpaceId() <= 0) {
                return Result.error("必须指定有效的所属空间");
            }

            // 检查用户是否有编辑权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasEditPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有在该知识空间创建文档的权限");
            // }

            // 检查文档名称是否已存在
            if (documentService.isDocumentNameExists(document.getDocumentName(), document.getSpaceId())) {
                return Result.error("该空间中已存在同名文档");
            }

            document.setCreatorUsername(username);
            int result = documentService.createDocument(document);
            if (result > 0) {
                return Result.success("文档创建成功");
            } else {
                return Result.error("文档创建失败");
            }
        } catch (Exception e) {
            return Result.error("创建文档失败: " + e.getMessage());
        }
    }

    /**
     * 更新文档信息
     */
    @PutMapping("/{documentId}")
    public Result updateDocument(@PathVariable Integer documentId, @RequestBody Document document,
            @RequestParam String username) {
        try {
            if (documentId == null || documentId <= 0) {
                return Result.error("文档ID不能为空或无效");
            }
            if (document == null) {
                return Result.error("文档信息不能为空");
            }
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }

            Document existingDoc = documentService.getDocumentById(documentId);
            if (existingDoc == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有编辑权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasEditPermission(existingDoc.getSpaceId(),
            // username)) {
            // return Result.error("没有编辑该文档的权限");
            // }

            document.setDocumentId(documentId);
            document.setSpaceId(existingDoc.getSpaceId()); // 保持原空间ID
            int result = documentService.updateDocument(document);
            if (result > 0) {
                return Result.success("文档更新成功");
            } else {
                return Result.error("文档更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新文档失败: " + e.getMessage());
        }
    }

    /**
     * 删除文档
     */
    @DeleteMapping("/{documentId}")
    public Result deleteDocument(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            if (documentId == null || documentId <= 0) {
                return Result.error("文档ID不能为空或无效");
            }
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }

            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有编辑权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasEditPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有删除该文档的权限");
            // }

            int result = documentService.deleteDocument(documentId);
            if (result > 0) {
                return Result.success("文档删除成功");
            } else {
                return Result.error("文档删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除文档失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户收藏的文档
     */
    @GetMapping("/favorites")
    public Result getFavoriteDocuments(@RequestParam String username) {
        try {
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }

            List<Document> documents = documentService.getFavoriteDocuments(username);
            // 为每个文档添加空间名称信息
            List<Map<String, Object>> documentsWithSpaceInfo = new ArrayList<>();
            for (Document doc : documents) {
                Map<String, Object> docInfo = new HashMap<>();
                docInfo.put("documentId", doc.getDocumentId());
                docInfo.put("documentName", doc.getDocumentName());
                docInfo.put("spaceId", doc.getSpaceId());

                // 获取空间名称
                try {
                    KnowledgeSpace space = knowledgeSpaceService.getSpaceById(doc.getSpaceId());
                    docInfo.put("spaceName", space != null ? space.getSpaceName() : "未知空间");
                } catch (Exception e) {
                    docInfo.put("spaceName", "未知空间");
                }

                documentsWithSpaceInfo.add(docInfo);
            }
            return Result.success(documentsWithSpaceInfo);
        } catch (Exception e) {
            return Result.error("获取收藏文档失败: " + e.getMessage());
        }
    }

    /**
     * 添加文档收藏
     */
    @PostMapping("/{documentId}/favorite")
    public Result addFavorite(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            if (documentId == null || documentId <= 0) {
                return Result.error("文档ID不能为空或无效");
            }
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }

            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }

            int result = documentService.addDocumentFavorite(documentId, username);
            if (result > 0) {
                return Result.success("收藏成功");
            } else {
                return Result.error("收藏失败");
            }
        } catch (Exception e) {
            return Result.error("收藏文档失败: " + e.getMessage());
        }
    }

    /**
     * 取消文档收藏
     */
    @DeleteMapping("/{documentId}/favorite")
    public Result removeFavorite(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            if (documentId == null || documentId <= 0) {
                return Result.error("文档ID不能为空或无效");
            }
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }

            int result = documentService.removeDocumentFavorite(documentId, username);
            if (result > 0) {
                return Result.success("取消收藏成功");
            } else {
                return Result.error("取消收藏失败");
            }
        } catch (Exception e) {
            return Result.error("取消收藏失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户最近访问的文档
     */
    @GetMapping("/recent")
    public Result getRecentDocuments(@RequestParam String username, @RequestParam(defaultValue = "10") Integer limit) {
        try {
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (limit == null || limit <= 0) {
                limit = 10;
            }

            List<Document> documents = documentService.getRecentDocuments(username, limit);

            // 为每个文档添加spaceName信息
            List<Map<String, Object>> documentsWithSpaceName = new ArrayList<>();
            for (Document doc : documents) {
                Map<String, Object> docMap = new HashMap<>();
                docMap.put("documentId", doc.getDocumentId());
                docMap.put("documentName", doc.getDocumentName());
                docMap.put("documentType", doc.getDocumentType());
                docMap.put("spaceId", doc.getSpaceId());
                docMap.put("visitTime", doc.getVisitTime());

                // 获取空间名称
                if (doc.getSpaceId() != null) {
                    KnowledgeSpace space = knowledgeSpaceService.getSpaceById(doc.getSpaceId());
                    if (space != null) {
                        docMap.put("spaceName", space.getSpaceName());
                    }
                }

                documentsWithSpaceName.add(docMap);
            }

            return Result.success(documentsWithSpaceName);
        } catch (Exception e) {
            return Result.error("获取最近访问文档失败: " + e.getMessage());
        }
    }

    // ========== 在线编辑功能 ==========

    /**
     * 开始编辑文档
     */
    @PostMapping("/{documentId}/edit/start")
    public Result startEdit(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有编辑权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasEditPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有编辑该文档的权限");
            // }

            String sessionId = documentService.startEditSession(documentId, username);
            return Result.success(sessionId);
        } catch (Exception e) {
            return Result.error("开始编辑失败: " + e.getMessage());
        }
    }

    /**
     * 结束编辑文档
     */
    @PostMapping("/edit/{sessionId}/end")
    public Result endEdit(@PathVariable String sessionId, @RequestParam String username) {
        try {
            documentService.endEditSession(sessionId, username);
            return Result.success("编辑会话已结束");
        } catch (Exception e) {
            return Result.error("结束编辑失败: " + e.getMessage());
        }
    }

    /**
     * 保存文档内容
     */
    @PostMapping("/{documentId}/save")
    public Result saveDocument(@PathVariable Integer documentId,
            @RequestParam String username,
            @RequestBody Map<String, Object> requestBody) {
        String content = (String) requestBody.get("content");
        String editSummary = (String) requestBody.get("editSummary");
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有编辑权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasEditPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有编辑该文档的权限");
            // }

            int result = documentService.saveDocumentWithVersion(documentId, content, username, editSummary);
            if (result > 0) {
                return Result.success("文档保存成功");
            } else {
                return Result.error("文档保存失败");
            }
        } catch (Exception e) {
            return Result.error("保存文档失败: " + e.getMessage());
        }
    }

    /**
     * 自动保存草稿
     */
    @PostMapping("/{documentId}/draft")
    public Result autoSaveDraft(@PathVariable Integer documentId,
            @RequestParam String username,
            @RequestBody Map<String, Object> requestBody) {
        String content = (String) requestBody.get("content");
        String sessionId = (String) requestBody.get("sessionId");
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有编辑权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasEditPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有编辑该文档的权限");
            // }

            documentService.autoSaveDraft(documentId, content, username, sessionId);
            return Result.success("草稿保存成功");
        } catch (Exception e) {
            return Result.error("保存草稿失败: " + e.getMessage());
        }
    }

    /**
     * 获取文档版本历史
     */
    @GetMapping("/{documentId}/versions")
    public Result getDocumentVersions(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }

            return Result.success(documentService.getDocumentVersions(documentId));
        } catch (Exception e) {
            return Result.error("获取版本历史失败: " + e.getMessage());
        }
    }

    // ========== 文档内容获取 ==========

    /**
     * 获取文档原始内容
     */
    @GetMapping("/{documentId}/content")
    public Result getDocumentContent(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }

            // 记录访问历史
            documentService.recordDocumentAccess(documentId, username);

            // 返回文档内容
            Map<String, Object> contentData = new HashMap<>();
            contentData.put("content", document.getContent());
            contentData.put("documentType", document.getDocumentType());
            contentData.put("fileExtension", document.getFileExtension());
            contentData.put("mimeType", document.getMimeType());

            return Result.success(contentData);
        } catch (Exception e) {
            return Result.error("获取文档内容失败: " + e.getMessage());
        }
    }

    /**
     * 下载文档文件（直接返回文件内容，用于PDF和Word预览）
     */
    @GetMapping("/{documentId}/file")
    public ResponseEntity<byte[]> downloadDocumentFile(@PathVariable Integer documentId,
            @RequestParam String username) {
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return ResponseEntity.notFound().build();
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            // }

            // 记录访问历史
            documentService.recordDocumentAccess(documentId, username);

            // 获取文件内容
            byte[] fileContent = documentService.getDocumentFileContent(documentId);
            if (fileContent == null) {
                return ResponseEntity.notFound().build();
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            if (document.getMimeType() != null) {
                headers.setContentType(MediaType.parseMediaType(document.getMimeType()));
            }
            headers.setContentLength(fileContent.length);

            // 对于PDF文件，设置inline显示
            if ("pdf".equalsIgnoreCase(document.getFileExtension())) {
                headers.setContentDisposition(ContentDisposition.inline()
                        .filename(document.getDocumentName() + "." + document.getFileExtension())
                        .build());
            } else {
                headers.setContentDisposition(ContentDisposition.attachment()
                        .filename(document.getDocumentName() + "." + document.getFileExtension())
                        .build());
            }

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileContent);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // ========== Markdown功能 ==========

    /**
     * 获取Markdown文档的HTML预览
     */
    @GetMapping("/{documentId}/preview")
    public Result getMarkdownPreview(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }

            String htmlContent = documentService.getMarkdownPreview(documentId);

            // 返回包含html和markdown内容的对象
            Map<String, Object> previewData = new HashMap<>();
            previewData.put("html", htmlContent);
            previewData.put("markdown", document.getContent());

            return Result.success(previewData);
        } catch (Exception e) {
            return Result.error("获取预览失败: " + e.getMessage());
        }
    }

    /**
     * 生成Markdown文档目录
     */
    @GetMapping("/{documentId}/toc")
    public Result generateToc(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }

            String toc = documentService.generateMarkdownToc(documentId);
            return Result.success(toc);
        } catch (Exception e) {
            return Result.error("生成目录失败: " + e.getMessage());
        }
    }

    /**
     * 提取Markdown文档中的资源
     */
    @GetMapping("/{documentId}/resources")
    public Result extractResources(@PathVariable Integer documentId, @RequestParam String username) {
        try {
            Document document = documentService.getDocumentById(documentId);
            if (document == null) {
                return Result.error("文档不存在");
            }

            // 检查用户是否有查看权限 - 暂时禁用权限控制
            // if (!knowledgeSpaceService.hasViewPermission(document.getSpaceId(),
            // username)) {
            // return Result.error("没有访问该文档的权限");
            // }

            DocumentService.DocumentResourceInfo resourceInfo = documentService.extractMarkdownResources(documentId);
            return Result.success(resourceInfo);
        } catch (Exception e) {
            return Result.error("提取资源失败: " + e.getMessage());
        }
    }

    /**
     * 实时预览Markdown内容（不保存到数据库）
     */
    @PostMapping("/markdown/preview")
    public Result previewMarkdown(@RequestParam String content) {
        try {
            String htmlContent = markdownService.markdownToHtml(content);
            return Result.success(htmlContent);
        } catch (Exception e) {
            return Result.error("预览失败: " + e.getMessage());
        }
    }
}
